﻿using MediatR;
using NPOI.SS.Formula.Functions;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PrenatalCheckup
{
    /// <summary>
    /// 妊检列表
    /// </summary>
    public class SearchPrenatalCheckupHandler : IRequestHandler<SearchPrenatalCheckupCommand, Result<PageResultDto<PrenatalCheckupDtos>>>
    {
        /// <summary>
        /// 妊检结果仓储
        /// </summary>
        private readonly IBaseRepository<PregnancyTestResults> _pregnancyTestResultRepository;

        /// <summary>
        /// 妊检方式仓储
        /// </summary>
        private readonly IBaseRepository<PregnancyTestType> _pregnancyTestTypeRepository;

        /// <summary>
        /// 妊检仓储
        /// </summary>
        private readonly IBaseRepository<PrenatalCheckups> _prenatalCheckupsRepository;

        /// <summary>
        /// 猪只档案仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> _basicInformationRepository;

        /// <summary>
        /// 栋舍管理仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> _bedroomRepository;

        /// <summary>
        /// 栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> _fieldsRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchPrenatalCheckupHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="pregnancyTestResultRepository"></param>
        /// <param name="pregnancyTestTypeRepository"></param>
        /// <param name="prenatalCheckupsRepository"></param>
        /// <param name="basicInformationRepository"></param>
        /// <param name="bedroomRepository"></param>
        /// <param name="fieldsRepository"></param>
        /// <param name="logger"></param>
        public SearchPrenatalCheckupHandler(IBaseRepository<PregnancyTestResults> pregnancyTestResultRepository,
                                            IBaseRepository<PregnancyTestType> pregnancyTestTypeRepository,
                                            IBaseRepository<PrenatalCheckups> prenatalCheckupsRepository,
                                            IBaseRepository<BasicInformation> basicInformationRepository,
                                            IBaseRepository<Bedrooms> bedroomRepository,
                                            IBaseRepository<Fields> fieldsRepository,
                                            ILogger<SearchPrenatalCheckupHandler> logger)
        {
            _pregnancyTestResultRepository = pregnancyTestResultRepository;
            _pregnancyTestTypeRepository = pregnancyTestTypeRepository;
            _prenatalCheckupsRepository = prenatalCheckupsRepository;
            _basicInformationRepository = basicInformationRepository;
            _bedroomRepository = bedroomRepository;
            _fieldsRepository = fieldsRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取妊检列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<PrenatalCheckupDtos>>> Handle(SearchPrenatalCheckupCommand request, CancellationToken cancellationToken)
        {
            //返回值
            var result = new Result<PageResultDto<PrenatalCheckupDtos>>() { Code = (int)CommonErrorCode.Search };
            //分页
            var page = new PageResultDto<PrenatalCheckupDtos>() { TotalCount = 0, PageCount = 0, List = new List<PrenatalCheckupDtos>() };
            try
            {
                var query = (from a in await _prenatalCheckupsRepository.GetAll()
                             join b in await _pregnancyTestResultRepository.GetAll() on a.PregnancyTestResultId equals b.PregnancyTestResultId
                             join c in await _pregnancyTestTypeRepository.GetAll() on a.PregnancyTestTypeId equals c.PregnancyTestTypeId
                             join d in await _basicInformationRepository.GetAll() on a.BasicInforId equals d.BasicInforId
                             join e in await _bedroomRepository.GetAll() on a.TurnBuilding equals e.BedroomId
                             join f in await _fieldsRepository.GetAll() on a.TurnColumn equals f.FieldId
                             where (a.IsPrenatalCheckUp == 1)
                             select new PrenatalCheckupDtos()
                             {
                                 PrenatalCheckupId = a.PrenatalCheckupId,
                                 DocumentNumber = a.DocumentNumber,
                                 SerialNumber = a.SerialNumber,
                                 BasicInforId = a.BasicInforId,
                                 PregnancyTestResultId = a.PregnancyTestResultId,
                                 PregnancyTestTypeId = a.PregnancyTestTypeId,
                                 ParityNumber = a.ParityNumber,
                                 CurrentBuilding = a.CurrentBuilding,
                                 Currentfield = a.Currentfield,
                                 TurnBuilding = a.TurnBuilding,
                                 TurnColumn = a.TurnColumn,
                                 Principal = a.Principal,
                                 PregnancyTestDate = a.PregnancyTestDate,
                                 IsPrenatalCheckUp = a.IsPrenatalCheckUp,
                                 CreatedOwner = a.CreatedOwner,
                                 CreatedTime = a.CreatedTime,
                                 UpdateOwner = a.UpdateOwner,
                                 UpdateTime = a.UpdateTime,
                                 ExamineOwner = a.ExamineOwner,
                                 ExamineTime = a.ExamineTime,
                                 EarNumber = d.EarNumber,//耳号
                                 PregnancyTestResultName = b.PregnancyTestResultName,//妊检结果
                                 PregnancyTestTypeName = c.PregnancyTestTypeName,//妊检方式
                                 BedroomName = e.BedroomName,//栋舍
                                 FieldName = f.FieldName//栏位
                             });
                //开始日期查询
                if (request.StartTime != null)
                {
                    query = query.Where(x => x.PregnancyTestDate >= request.StartTime);
                }
                //结束日期查询
                if (request.EndTime != null)
                {
                    query = query.Where(x => x.PregnancyTestDate <= request.EndTime);
                }
                //种母耳号查询
                if (request.BasicInforId != 0)
                {
                    query = query.Where(x => x.BasicInforId == request.BasicInforId);
                }
                //负责人查询
                if (!string.IsNullOrEmpty(request.Principal))
                {
                    query = query.Where(x => x.Principal.Contains(request.Principal));
                }
                //妊检结果查询
                if (request.PregnancyTestResultId != 0)
                {
                    query = query.Where(x => x.PregnancyTestResultId == request.PregnancyTestResultId);
                }
                //同胎数查询
                if (request.ParityNumber != -1)
                {
                    query = query.Where(x => x.ParityNumber == request.ParityNumber);
                }
                //总条数
                page.TotalCount = query.Count();
                //总页数
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
                //跳过几条 显示几条
                page.List = query.OrderBy(x => x.PregnancyTestDate).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                if (page.List.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取妊检列表成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取妊检列表异常" + ex.Message;
                _logger.LogError("获取妊检列表异常" + ex.Message);
            }
            return result;
        }
    }
}
